package com.gh.netty.server.handler;

import com.alibaba.fastjson.JSONObject;

import org.apache.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 处理服务端 channel.
 * @author hugx
 * @create 2018-09-29 14:22
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)

    private static final Logger log=Logger.getLogger(DiscardServerHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        // 默默地丢弃收到的数据
        log.info("channelRead() of DiscardServerHandler    默默地丢弃收到的数据");
//        ((ByteBuf) msg).release(); // (3)
        ByteBuf in= (ByteBuf) msg;
        log.info(String.format("=== %s",in.toString(CharsetUtil.UTF_8)));
        JSONObject json=new JSONObject();
        json.put("cmd",0x03);
        json.put("name","ADS");
        json.put("num",89);

         ctx.write(json.toJSONString());
         ctx.flush();
//        in.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // 当出现异常就关闭连接
        log.info("exceptionCaught() of DiscardServerHandler");
        cause.printStackTrace();
        ctx.close();
    }
}
